package com.bz.websocket;

import com.bz.websocket.utils.ObjectMapperUtil;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.client.WebClient;

import java.util.Objects;

import reactor.core.publisher.Mono;

/**
 * @author zhongyongbin
 * @since 2021/5/11
 */
@Component
public final class AuthManager {

    private String authUrl;

    @Autowired
    private WebClient webClient;

    /**
     * 身份认证
     *
     * @param protocol 请求协议
     * @return 认证结果
     */
    public Mono<Boolean> auth(RequestProtocol protocol) {
        return webClient.post()
                .uri(authUrl)
                .contentType(MediaType.APPLICATION_JSON)
                .bodyValue(ObjectMapperUtil.transferToString(new AuthRequest(protocol.getToken(), protocol.getDevice())))
                .retrieve()
                .bodyToMono(String.class)
                .map(string -> {
                    AuthResponse response = ObjectMapperUtil.transferToObject(string, AuthResponse.class);
                    if (Objects.isNull(response)) {
                        return false;
                    }
                    return response.getResult();
                });
    }

    public void setAuthUrl(String authUrl) {
        this.authUrl = authUrl;
    }
}
